<template>
  <div class="moveBox">
    <rj-modal
      :visible="visible"
      :title="$t('enetPwd.chooseGroup')"
      @ok="clickOk"
      @cancel="clickCancle"
      :width="450"
      :maskClosable="false"
      :okText="$t('upgradeLog.ok')"
      :cancelText="$t('upgradeLog.canel')"
    >
      <div class="treecontrol">
        <a-input-search
          v-model="searchValue"
          :placeholder="$t('enetPwd.enterKeywords')"
          @change="onSearch"
        ></a-input-search>
        <!-- selectedKeys是选中项key的集合，expandedKeys是展开项key的集合 replaceFields替换对应treeData中对应属性 -->
        <a-tree
          :treeData="treeData"
          :selectedKeys="selectedKeys"
          :expandedKeys="expandedKeys"
          @expand="onExpand"
          :autoExpandParent="autoExpandParent"
          :replaceFields="replaceFields"
          @select="onSelect"
          show-icon
        >
          <i slot="LOCATION" class="ic- ic-device-internet" />
          <i slot="BUILDING" class="ic- ic-tree-network" />
          <i slot="DEVICE" class="ic- ic-tree-device" />
          <template slot="title" slot-scope="{ name }">
            <span
              v-html="
                name.replace(
                  new RegExp(searchValue, 'g'),
                  '<span style=background-color:#cfe4ff>' +
                    searchValue +
                    '</span>'
                )
              "
            ></span>
          </template>
        </a-tree>
      </div>
    </rj-modal>
    <rj-modal
      :visible="confirmVisible"
      @ok="submit"
      @cancel="confirmVisible = false"
      :width="300"
      :maskClosable="false"
      :okText="$t('upgradeLog.ok')"
      :cancelText="$t('upgradeLog.canel')"
    >
      <span style="letter-sapcing: 5px">{{
        $t('enetPwd.tip4', [this.targetNode.name])
      }}</span>
    </rj-modal>
  </div>
</template>
<script>
import { requestHttp, maccApi, zhugePoint } from '@utils/index';
import { RjModal } from '@components';
const treeData = [];
export default {
  name: 'GroupTree',
  data() {
    return {
      replaceFields: { title: 'name', children: 'subGroups' },
      expandedKeys: [],
      backupsExpandedKeys: [],
      autoExpandParent: false,
      checkedKeys: [],
      selectedKeys: [],
      searchValue: '',
      searchStr: '',
      treeData: [],
      //显隐
      confirmVisible: false,

      scopedSlots: { title: 'title' },
      //选中节点
      targetNode: {},
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    'rj-modal': RjModal,
  },
  created() {
    this.getgroupTree();
  },
  methods: {
    //确认回调
    clickOk() {
      if (JSON.stringify(this.targetNode) == '{}') {
        this.$message.warning(this.$t('deviceDetail.selectdevice'), 5);
      } else {
        this.confirmVisible = true;
      }
    },

    //取消回调
    clickCancle() {
      this.visible = false;
      this.searchValue = '';
    },

    //提交
    submit() {
      console.log(this.targetNode);
      console.log('提交');
    },
    async getgroupTree() {
      const res = await requestHttp({
        api: maccApi.GROUP_ALLTREE_GET_API,
        method: 'GET',
      });
      console.log(res);
      //subGroups=>children
      // let temp = JSON.stringify(res.groupgroupIds).replace(
      //   /subGroups/g,
      //   'children'
      // );
      // console.log('----------------');
      //this.treeData = JSON.parse(temp).children;
      this.treeData = res.groups.subGroups;
      //添加key=,slots=type
      this.recursion(this.treeData);
      //console.log(this.treeData);
    },

    //递归添加新属性
    recursion(arr) {
      arr.forEach((element) => {
        let key = element.groupId;
        this.$set(element, 'key', key);
        let slots = new Object();
        slots.icon = element.type;
        if (element.type == 'ROOT') {
          slots.icon = 'LOCATION';
        }
        this.$set(element, 'slots', slots);
        this.$set(element, 'scopedSlots', this.scopedSlots);
        if (element.subGroups && element.subGroups.length) {
          this.recursion(element.subGroups);
        } else return;
      });
    },

    onSearch() {
      var vm = this;
      //添加这行代码是为了只点击搜索才触发
      //vm.searchValue = vm.searchStr;
      //如果搜索值为空，则不展开任何项，expandedKeys置为空
      //如果搜索值不位空，则expandedKeys的值要为搜索值的父亲及其所有祖先
      if (vm.searchValue === '') {
        vm.expandedKeys = [];
      } else {
        //首先将展开项与展开项副本置为空
        vm.expandedKeys = [];
        vm.backupsExpandedKeys = [];
        //获取所有存在searchValue的节点
        let candidateKeysList = vm.getkeyList(vm.searchValue, vm.treeData, []);
        //遍历满足条件的所有节点
        candidateKeysList.map((item) => {
          //获取每个节点的母亲节点
          var key = vm.getParentKey(item, vm.treeData);
          //当item是最高一级，父key为undefined，将不放入到数组中
          //如果母亲已存在于数组中，也不放入到数组中
          if (key && !vm.backupsExpandedKeys.some((item) => item === key))
            vm.backupsExpandedKeys.push(key);
        });
        let length = this.backupsExpandedKeys.length;
        for (let i = 0; i < length; i++) {
          vm.getAllParentKey(vm.backupsExpandedKeys[i], vm.treeData);
        }
        vm.expandedKeys = vm.backupsExpandedKeys.slice();
      }
    },
    //获取节点中含有value的所有key集合
    getkeyList(value, tree, keyList) {
      //遍历所有同一级的树
      for (let i = 0; i < tree.length; i++) {
        let node = tree[i];
        //如果该节点存在value值则push
        if (node.name.indexOf(value) > -1) {
          keyList.push(node.key);
        }
        //如果拥有孩子继续遍历
        if (node.subGroups) {
          this.getkeyList(value, node.subGroups, keyList);
        }
      }
      //因为是引用类型，所有每次递归操作的都是同一个数组
      return keyList;
    },
    //该递归主要用于获取key的父亲节点的key值
    getParentKey(key, tree) {
      let parentKey, temp;
      //遍历同级节点
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.subGroups) {
          //如果该节点的孩子中存在该key值，则该节点就是我们要找的父亲节点
          //如果不存在，继续遍历其子节点
          if (node.subGroups.some((item) => item.key === key)) {
            parentKey = node.key;
          } else if ((temp = this.getParentKey(key, node.subGroups))) {
            //parentKey = this.getParentKey(key,node.children)
            //改进，避免二次遍历
            parentKey = temp;
          }
        }
      }
      return parentKey;
    },
    //获取该节点的所有祖先节点
    getAllParentKey(key, tree) {
      var parentKey;
      if (key) {
        //获得父亲节点
        parentKey = this.getParentKey(key, tree);
        if (parentKey) {
          //如果父亲节点存在，判断是否已经存在于展开列表里，不存在就进行push
          if (!this.backupsExpandedKeys.some((item) => item === parentKey)) {
            this.backupsExpandedKeys.push(parentKey);
          }
          //继续向上查找祖先节点
          this.getAllParentKey(parentKey, tree);
        }
      }
    },
    onExpand(expandedKeys) {
      //用户点击展开时，取消自动展开效果
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      console.log('onCheck', checkedKeys);
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys, info) {
      console.log('onSelect', info);
      this.targetNode = info.node.dataRef;
      //console.log(this.targetNode);
      this.selectedKeys = selectedKeys;
    },
  },
};
</script>
<style scope>
@import '//at.alicdn.com/t/font_2689451_vzkb0sls4l.css';
.treecontrol {
  color: black;
  text-align: left;
}
.ant-input-search {
  width: 100% !important;
}
.ant-tree {
  height: 300px;
  overflow: auto;
  margin: 10px 0;
}
/* .ant-tree::-webkit-scrollbar {
  display: none;
} */
</style>
